package com.maserb.monitor.common;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	public static String getPostData(String url, Map<String, String> params) {
		PostMethod postMethod = null;
        try{
        	postMethod = null;
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(30*1000);	//连接超时时间
			client.getHttpConnectionManager().getParams().setSoTimeout(60*1000);	//读取数据超时时间(3分钟)
			
			postMethod = new PostMethod(url);
			postMethod.getParams().setContentCharset("utf-8");
			postMethod.getParams().setParameter("http.protocol.content-charset", "UTF-8");
			postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			if(params != null){
				//将所有参数存入postMethod
				for(Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
					String key = it.next();
					postMethod.setParameter(key, params.get(key));
				}
			}
			
            int httpState = client.executeMethod(postMethod);
			InputStream resStream = postMethod.getResponseBodyAsStream();  
            BufferedReader br = new BufferedReader(new InputStreamReader(resStream,"UTF-8"));  
            StringBuffer resBuffer = new StringBuffer();  
            String resTemp = "";  
            while((resTemp = br.readLine()) != null){  
                resBuffer.append(resTemp);  
            }  
            String data = resBuffer.toString(); 
			//如果服务器返回正常，表示未出现异常。
			if(HttpStatus.SC_OK == httpState){
				return data;
			}else{
				return "{\"success\":false, \"msg\":\"httpclient超时"+data+"\"}";
			}
		
        } catch (IllegalArgumentException e) {
    		logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"IllegalArgumentException\"}";
		} catch (HttpException e) {
			logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"HttpException\"}";
		} catch (IOException e) {
			logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"IOException\"}";
		}finally{
			if(null != postMethod){
				postMethod.releaseConnection();
			}
		}
	}
	
	public static String getGetData(String url) {
		return getGetData(url, null);
	}
	
	public static String getGetData(String url, Map<String, String> params) {
		GetMethod getMethod = null;
		StringBuilder sb = new StringBuilder(url);
        try{
        	getMethod = null;
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(30*1000);	//连接超时时间
			client.getHttpConnectionManager().getParams().setSoTimeout(60*1000);	//读取数据超时时间(3分钟)
			
			//设置GET方法参数
			boolean first = true;
			if(params != null){
				for(Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
					String key = it.next();
					if(first) {
						sb.append("?");
						first = false;
					} else {
						sb.append("&");
					}
					sb.append(key);
					sb.append("=");
					sb.append(params.get(key));
				}
			}
			
			getMethod = new GetMethod(sb.toString());
			getMethod.getParams().setContentCharset("utf-8");
			getMethod.getParams().setParameter("http.protocol.content-charset", "UTF-8");

            int httpState = client.executeMethod(getMethod);
			InputStream resStream = getMethod.getResponseBodyAsStream();  
            BufferedReader br = new BufferedReader(new InputStreamReader(resStream,"UTF-8"));  
            StringBuffer resBuffer = new StringBuffer();  
            String resTemp = "";  
            while((resTemp = br.readLine()) != null){  
                resBuffer.append(resTemp);  
            }  
            String data = resBuffer.toString(); 
			//如果服务器返回正常，表示未出现异常。
			if(HttpStatus.SC_OK == httpState){
				return data;
			}else{
				return "{\"success\":false, \"msg\":\"httpclient超时"+data+"\"}";
			}
		
        } catch (IllegalArgumentException e) {
    		logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"IllegalArgumentException\"}";
		} catch (HttpException e) {
			logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"HttpException\"}";
		} catch (IOException e) {
			logger.error("连接" + url + "发生异常...", e);
			return "{\"success\":false, \"msg\":\"IOException\"}";
		}finally{
			if(null != getMethod){
				getMethod.releaseConnection();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		String content = "测试中文内容";
		String url = "http://112.124.30.39:8888/sms.aspx?action=send&userid=86&account=ykyy&password=yk880129&mobile=15802857518&content="+URLEncoder.encode(content, "UTF-8")+"&sendTime=&checkcontent=1";
		
		String result = getGetData(url);
		
		System.out.println(result);
	}
}
